home *** CD-ROM | disk | FTP | other *** search
Text File | 1990-04-27 | 2.1 KB | 71 lines | [TEXT/GEOL] |
- Item 4603899 24-April-90 12:01PDT
-
- From: D0532 Aidea Systems, Don Park,PRT
-
- To: CPLUS.DEV$ C++ Interest List--Developers
- CPLUS.APPLE$ C++ Interest List--Apple Employees
-
- Sub: Handling Constructor Errors?
-
- I have been suffering of late due to lack of decent error/exception handling
- mechanism in C++. Rather than boil my brain alone, I would like to get some
- input from you guys.
-
- One common situation I have is error handling within constructors of classes
- with pointer/reference to other objects created by the class. For example:
-
- class AllocatingClass
- {
- public:
- AllocatingClass ( void ) { buffer = malloc(BUFFERSIZE); }
- ~AllocatingClass ( void ) { free(buffer); }
- Validate ( void ) { return (buffer != NULL); }
- DoSomething ( void ) { // do something with buffer }
-
- private:
- void * buffer; // Pointer to a block of memory
- };
-
- main ()
- {
- AllocatingClass c; // stack instance
- AllocatingClass * p; // free store instance
-
- p = new AllocatingClass;
-
- // If malloc() call in the constructor failed, buffer will be NULL yet
- // p will NOT be NULL. One must make additional call to make sure the
- // object got created properly.
-
- if (c.Validate())
- c.DoSomething();
- if (p->Validate())
- p->DoSomething();
-
- delete p;
- }
-
- As you can see, this situation is indeed very common. Is there a better way to
- handle this situation? I think nothing short of an exception handling
- mechanism will do.
-
- It is interesting to note that the constructor is rebuilt by CFront to
- following form:
-
- struct AllocatingClass *
- AllocatingClass::AllocatingClass ( register struct AllocatingClass * this )
- {
- if (this || (this = ::operator new(sizeof(struct AllocatingClass))))
- {
- this->buffer = malloc(BUFFERSIZE);
- }
- return this;
- }
-
- It is also interesting to note that none of the C++ books seem to discuss this
- problem when a predicate member function like Validate() is as much a part of a
- class as constructors and destructor.
-
- Don Park
-
-